<?php 
error_reporting(0);	

require_once("php/database.include.php");
		
$groupName = $_GET['groupName'];
$userName = $_GET['userName'];
$message = $_GET['message'];
$retentionMode = $_GET['retentionMode'];
$expirationDate = $_GET['expirationDate'];

//debug only
echo 'groupName: ' . $groupName . '<br/>userName: ' . $userName . '<br/>message: ' . $message . '<br/>retentionMode: ' . $retentionMode. '<br/>expirationDate: ' . $expirationDate . '<br/>';

if (empty($groupName) && empty($userName) && empty($message) && empty($retentionMode) && empty($expirationDate) ) {
	echo 'no data';
	return 'no data';
	exit;
}

$inputErrors = validateInput($groupName, $userName, $message, $retentionMode, $expirationDate);

if (strcmp('', $inputErrors) == 0 ) {
	//echo 'calling createGroup';
	return sendGroupMessage ($conn, $groupName, $userName, $message, $retentionMode, $expirationDate);
}
else {
	echo  "Create%20group%20failed.%20" . $inputErrors;
	return ("Create%20group%20failed.%20" . $inputErrors);
}

function validateInput($groupName, $userName, $message, $retentionMode, $expirationDate) {
	$retVal = '';
	if (empty($groupName)) {
		$retVal .= 'groupName%20cannot%20be%20mpty .';
	}
	if (empty($userName)) {
		$retVal .= 'userName%20cannot%20be%20empty .';
	}
	if (empty($message)) {
		$retVal .= 'message%20cannot%20be%20empty .';
	}
	if (empty($retentionMode)) {
		$retVal .= 'retentionMode%20key%20cannot%20be%20empty .';
	}
	if (empty($expirationDate)) {
		$retVal .= 'expirationDate%20cannot%20be%20empty .';
	}
	
	echo $retVal;
	return $retVal;
}


function sendGroupMessage( $conn, $groupName, $userName, $message, $retentionMode, $expirationDate ) {
	
	try {		
		$conn->beginTransaction();

		//Create new group		
		$stmt = $conn->prepare(' INSERT INTO `message` (group_name, user_name, message, retention_mode, expiration_date ) VALUES (?, ?, ?, ?, ?) ');
		$sendMessageSuccess = $stmt->execute( array( $groupName, $userName, $message, $retentionMode, $expirationDate ) );				
		$conn->commit();

		echo "<br/>Success on sending message: " . $message;
		return "<br/>Success on sending message: " . $message;
	}	
	catch(PDOException $err) {
		$conn->rollBack();
		echo "<br/>Failure sending message: " . $message . ', ' . $err->getMessage();		
		return "<br/>Failure sending message: " . $message;
	}
	catch(Exception $err) 
	{
		$conn->rollBack();
		echo "<br/>Internal failure sending message: " . $message;
		return "Internal failure sending message: " . $message;
	}
}
?>
